<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity {
    // Будем хранить id и роль
    private $_id;
    private $_role;
    private $_faculty_id;

    // Данный метод вызывается один раз при аутентификации пользователя.
    public function authenticate() {
 
        $user = null;

        if(Professor::model()->exists('LOWER(email)=?', array(strtolower($this->username)))) {
            $this->_role = 'professor';
            
            $user = Professor::model()->find('LOWER(email)=?', array(strtolower($this->username)));
             $this->_faculty_id = $user->department->faculty_id;
            if($user->id == '1')
                    $this->_role = 'administrator';
        } else {
            if(Student::model()->exists('LOWER(email)=?', array(strtolower($this->username)))) {
                $this->_role = 'student';
                $user = Student::model()->find('LOWER(email)=?', array(strtolower($this->username)));

                $this->_faculty_id = $user->faculty_id;
            }
        }

        if(($user===null) or (md5(Yii::app()->params['salt'].$this->password)!==$user->password)) {
            $this->_role = 'guest';
            $this->errorCode = self::ERROR_USERNAME_INVALID;
        } else {
            // В качестве идентификатора будем использовать id
            $this->_id = $user->id;
            $this->setState('role', $this->_role);
            $this->setState('faculty_id',$this->_faculty_id);
            $this->setState('firstName', $user->firstName);
            $this->errorCode = self::ERROR_NONE;
        }
        return !$this->errorCode;
    }

    public function getId() {
        return $this->_id;
    }

/*    public function getRole() {
        return $this->_role;
    }
 */
}